package com.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

import com.easywan.core.EasyWanDES;
import com.easywan.exception.RuleErrorException;
import com.easywan.utils.Config;

public class VideoUploadServlet extends DefaultUploadServlet{
	private static final long serialVersionUID = 1L;
	private String filePath;
	@Override
	public String getFileName(String f) {
		filePath = super.getFileName(f);
		return filePath;
	}
	public String getFileCacheName(){
		return filePath;
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doPost(req, resp);
		@SuppressWarnings("unchecked")
		Map<String, Object> params = (Map<String, Object>) req.getAttribute("params");
		/*try {
			params = //getParams(req);
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (RuleErrorException e) {
			e.printStackTrace();
		}*/
		String videoPwd = EasyWanDES.DES((String) params.get("pwd"));
		String des = (String) params.get("des");
		String videoPath = getSavePath() + "/" + filePath;
		
		File file = new File(videoPath);
		File desFile = new File(getVideoDesPath() + "/" + filePath);
		File desFilePath =  new File(getVideoDesPath() + "/" + filePath.substring(0,filePath.lastIndexOf("/")));
		if(!desFilePath.exists()){
			desFilePath.mkdirs();
		}
		
		
		FileInputStream in = new FileInputStream(file);
		FileOutputStream out = new FileOutputStream(desFile);
		
		
		byte[] buffer = new byte[1024];
		
		if("des".equals(des)){
			System.out.println("启用压缩");
			in.read(buffer,0,videoPwd.getBytes().length);
			System.out.println(new String(buffer));
			/*in.read(buffer,0,videoPwd.getBytes().length);
			System.out.println(new String(buffer));*/
		}else{
			out.write(videoPwd.getBytes());
		}
		while(in.read(buffer) != -1){
			out.write(buffer);
		}
		out.flush();
		out.close();
	//	in.reset();
		in.close();
		
		String fileName = ((FileItem)(params.get("file1"))).getName();
		String fileRealName = filePath;
		//resp.getWriter().write(filePath);
		req.setAttribute("fileName", fileName);
		req.setAttribute("fileRealName", fileRealName);
		//resp.sendRedirect("/videoDown.do");
		//resp.flushBuffer();
		//resp.reset();
		req.getRequestDispatcher("/video.jsp").forward(req, resp);
	 	return;
	}
	public String getVideoDesPath(){
		return Config.get("videoDesPath");
	}
	
}
